import secrets
from sqlalchemy.orm import Session

from . import models, schemas


def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()

def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()

def get_user_by_api_key(db: Session, api_key: str):
    return db.query(models.User).filter(models.User.api_key == api_key).first()

def get_user_by_username(db: Session, username: str):
    return db.query(models.User).filter(models.User.username == username).first()

def create_user(db: Session, user: schemas.UserCreate):
    # 生成唯一的API Key
    api_key = f"aiproxy-user-{secrets.token_hex(16)}"
    db_user = models.User(
        username=user.username,
        token_balance=user.token_balance,
        api_key=api_key
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def update_token_balance(db: Session, user_id: int, token_update: schemas.TokenUpdate):
    db_user = get_user(db, user_id)
    if db_user:
        db_user.token_balance = token_update.token_balance
        db.commit()
        db.refresh(db_user)
    return db_user

def deduct_user_tokens(db: Session, user_id: int, amount: int):
    db_user = get_user(db, user_id)
    if db_user and db_user.token_balance >= amount:
        db_user.token_balance -= amount
        db.commit()
        db.refresh(db_user)
        return db_user
    return None # 表示余额不足或用户不存在
